package db_connect

import (
	"fmt"
	"scoce_estimate/data_process"
	"scoce_estimate/model"
	"scoce_estimate/status"
	"scoce_estimate/utils/database"
	"time"

	"gorm.io/gorm"
)

var db *gorm.DB

func init() {
	db = database.GetDB()
}

func UploadSolution(user *model.User, problem_id int, code_length int, source string) {
	// user := utils.Query("admin")
	if isSolutionExist(user, problem_id) {
		return
	}
	data_process.Insert(user.User_id, problem_id, -1, status.IN_QUEUE)
	solution := createSolution(user, problem_id, code_length)
	createSourceCode(solution, source)
	updateResult(solution)
}

func CreateUser(user_id string) (user *model.User) {
	user = &model.User{}
	db.Where("user_id=?", user_id).Find(user)
	if user.User_id == "" {
		user = &model.User{
			User_id:    user_id,
			Email:      "",
			Ip:         "localhost",
			Accesstime: time.Now(),
			Password:   "",
			Reg_time:   time.Now(),
			Nick:       user_id,
			School:     "ZhimaAosaiUniversity",
			Defunct:    "N",
		}
		db.Create(user)
	}

	return
}

/**
		PRIVATE
**/

func isSolutionExist(user *model.User, problem_id int) bool {
	res := data_process.GetScore(user.User_id, problem_id)
	if res.Status != status.NOT_IN_QUEUE {
		return true
	}
	return false
}

func createSolution(user *model.User, problem_id int, code_length int) *model.Solution {
	solution := &model.Solution{}
	solution.Problem_id = problem_id
	solution.User_id = user.User_id
	solution.Nick = user.Nick
	solution.In_date = time.Now()
	solution.Language = 1
	solution.Ip = "localhost"
	solution.Code_length = code_length
	solution.Result = 14

	db.Create(solution)
	if solution.Solution_id == 0 {
		fmt.Println("Create solution failed.")
	}

	return solution
}

func createSourceCode(solution *model.Solution, source string) {
	sc := &model.Source_code{Solution_id: solution.Solution_id, Source: source}
	scu := &model.Source_code_user{Solution_id: solution.Solution_id, Source: source}
	db.Create(sc)
	db.Create(scu)
}

func updateResult(solution *model.Solution) {
	db.Model(solution).Select("result").Updates(model.Solution{Result: 0})
}
